package com.example.word.ui.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;


import com.example.dict.R;
import com.example.word.bean.Dict;
import com.example.word.bean.StudyPlan;
import com.example.word.bean.User;
import com.example.word.util.HttpUtils;
import com.example.word.util.MessageUtils;
import com.example.word.util.Response;
import com.example.word.util.SPUtils;
import com.example.word.widget.ActionBar;

import org.litepal.crud.DataSupport;

import java.util.HashMap;
import java.util.Map;

/**
 * 登录页面
 */
public class LoginActivity extends Activity {
    private static final String TAG = "LoginActivity";
    private Activity activity;
    private ActionBar mTitleBar;//标题栏
    private EditText etAccount;//手机号
    private EditText etPassword;//密码
    private TextView tvRegister;//注册
    private Button btnLogin;//登录按钮
//    private RadioGroup rgType;//用户类型
//    private RadioButton rbUser;//用户类型
//    private RadioButton rbAdmin;//用户类型
    private CheckBox cbAgree;//用户协议
    private TextView tv_mm;//忘记密码
    public static String systemMessage = "系统消息: 您今日学习了0个单词，累计学习了0个单词，继续加油噢！";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activity = this;
        setContentView(R.layout.activity_login);//加载页面
        etAccount = (EditText) findViewById(R.id.et_account);//获取号
        etPassword = (EditText) findViewById(R.id.et_password);//获取密码
        tvRegister = (TextView) findViewById(R.id.tv_register);//获取注册
        tv_mm = (TextView) findViewById(R.id.tv_mm);//忘记密码
        btnLogin = (Button) findViewById(R.id.btn_login);//获取登录
//        rgType = findViewById(R.id.rg_type);
//        rbUser = findViewById(R.id.rb_user);
//        rbAdmin = findViewById(R.id.rb_admin);
        cbAgree = findViewById(R.id.cb_agree);//用户协议
        mTitleBar = (ActionBar) findViewById(R.id.myActionBar);
        mTitleBar.setData(activity, "登录", 0, 0, 0, getResources().getColor(R.color.colorPrimary), new ActionBar.ActionBarClickListener() {
            @Override
            public void onLeftClick() {
                finish();
            }

            @Override
            public void onRightClick() {
            }
        });
        // 设置主题
        if (!com.example.word.ui.activity.MainActivity.colorChange) {
            mTitleBar.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
            btnLogin.setBackground(getResources().getDrawable(R.drawable.btn_border_fill));
        } else {
            mTitleBar.setBackgroundColor(getResources().getColor(R.color.myColor));
            btnLogin.setBackground(getResources().getDrawable(R.drawable.btn_border_fill_my_color));
        }
        //rbUser.setChecked(true);//默认选择用户RadioButton
        //注册
        tvRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转到注册页面
                Intent intent = new Intent(activity, RegisterActivity.class);
                startActivity(intent);
            }

        });
        //忘记密码
        tv_mm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(activity, PasswordActivity.class);
                startActivity(intent);
            }
        });
        //选择类型
//        rgType.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
//            @Override
//            public void onCheckedChanged(RadioGroup group, int checkedId) {
//                SPUtils.put(activity, SPUtils.IS_ADMIN, checkedId == R.id.rb_admin);
//            }
//        });
        //设置点击按钮
        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //获取请求参数
                String account = etAccount.getText().toString();
                String password = etPassword.getText().toString();
                Boolean isAdmin = (Boolean) SPUtils.get(activity, SPUtils.IS_ADMIN, false);

                if ("".equals(account)) {//账号不能为空
                    MessageUtils.show("账号不能为空!", activity);
                    return;
                }
                if ("".equals(password)) {//密码为空
                    MessageUtils.show("密码为空!", activity);
                    return;
                }
                if (!cbAgree.isChecked()) {
                    MessageUtils.show("请同意用户协议!", activity);
                    return;
                }
                ProgressDialog dialog = new ProgressDialog(activity);
                dialog.setMessage("正在验证账号···");
                dialog.show();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
//                        if ("admin".equals(account)) {
//                            MessageUtils.show("管理员功能开发中！", activity);
//                            return;
//                        }
                        User user = DataSupport.where("account = ?", account).findFirst(User.class);
                        if (user == null) {
                            MessageUtils.show("账号不存在，登录失败！", activity);
                            dialog.dismiss();
                            return;
                        }
                        if (!password.equals(user.getPassword())) {
                            MessageUtils.show("密码错误！", activity);
                            dialog.dismiss();
                        } else {
                            // 处理请求成功的情况
                            MessageUtils.show("恭喜你，登录成功！", activity);

                            // 登录成功，如果没有学习计划，设置默认学习计划
                            int count = DataSupport.where("account = ?", account).count(StudyPlan.class);
                            if (count == 0) {
                                StudyPlan studyPlan = new StudyPlan();
                                studyPlan.setAccount(account);
                                studyPlan.setDict(Dict.findFirst(Dict.class).getTitle());
                                studyPlan.setDayTask(5);
                                studyPlan.save();
                            }
                            // 加载当前用户学习情况 dayTask,todayCount,totalCount, currentUserDict;
                            StudyPlan studyPlan = StudyPlan.queryCurrentUserPlan(account);
                            systemMessage = String.format("系统消息: 您今日学习了%s个单词，累计学习了%s个单词，继续加油噢！", studyPlan.getTodayCount(), studyPlan.getTotalCount());

                            SPUtils.put(activity, SPUtils.IS_ADMIN, "admin".equals(user.getAccount()));
                            SPUtils.put(LoginActivity.this, "account", user.getAccount());

                            Intent intent = new Intent(activity, MainActivity.class);
                            startActivity(intent);
                            finish();
                            dialog.dismiss();
                        }
                    }
//                    @Override
//                    public void run() {
//                        Map<String, String> loginParam = new HashMap<>();
//                        loginParam.put("account", account);
//                        loginParam.put("password", password);
//                        // 调用 API 客户端的方法
//                        HttpUtils.sendGetRequest("/userLogin", loginParam, User.class, new HttpUtils.ApiCallback<User>() {
//                            @Override
//                            public void onSuccess(Response<User> response) {
//                                User user = (User)response.getData();
//                                // 处理请求成功的情况
//                                SPUtils.put(activity, SPUtils.IS_ADMIN, "admin".equals(user.getAccount()));
//                                SPUtils.put(LoginActivity.this, "account", user.getAccount());
//                                Intent intent = new Intent(activity, MainActivity.class);
//                                startActivity(intent);
//                                MessageUtils.show("恭喜你，登录成功！", activity);
//                                finish();
//                                dialog.dismiss();
//                            }
//
//                            @Override
//                            public void onFailure(Response<User> response) {
//                                // 处理请求失败的情况
//                                MessageUtils.show(response.getMsg(), activity);
//                                dialog.dismiss();
//                            }
//                        });
//                    }
                }, 505);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();//刷新
    }
}
